<template>
  <div class="seat">
    <div class="w">
      <div class="container" ref="container">
        <div class="top clearfix">
          <el-breadcrumb separator-class="el-icon-arrow-right" class="fl">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>管理座位</el-breadcrumb-item>
          </el-breadcrumb>
          <div class="btns fr">
            <el-button v-if="isAdmin && (Authcode==101 || Authcode==201)" plain class="bmks" type="info" @click="$router.push({name: 'bmks'})">管理部门</el-button>
            <el-button class="admin" type="primary" @click="$router.push({name: 'admin'})">管理员工</el-button>
            <el-button v-if="isLogin && Authcode!=101" class="personal" type="info" @click="$router.push({name: 'personal'})">个人信息</el-button>
            <el-button type="danger" class="loginOut" @click="outLogin">退出</el-button>
          </div>
        </div>

        <!-- 顶部搜索 -->
        <el-col :span="24" class="header-op" style="height: 62px;">
          <el-form :inline="true">
            <!-- <el-form-item>
              <el-select clearable v-model="params.department" placeholder="部门" @change="changeDepartment" @clear="init" :disabled="lockD">
                <el-option v-for="(item,index) in options.department" :key="index" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item>
              <el-select clearable v-model="params.section" placeholder="科室" @clear="search" :disabled="lockS">
                <el-option v-for="(item,index) in options.section" :key="index" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-select v-model="hasman" placeholder="是否空座">
                <el-option v-for="(item,index) in options.hasman" :key="index" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item>
              <el-select v-model="params.codition" placeholder="搜索类型">
                <el-option v-for="(item,index) in options.codition" :key="index" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-input placeholder="搜索" v-model="searchText" clearable @keyup.enter.native="goSearch" @clear="goSearch">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="goSearch">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addSeat">新增</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" plain @click="delSelections" v-if="Authcode == 101">批量删除</el-button>
            </el-form-item>
            <!-- <el-form-item>
            <el-button type="danger" plain>批量冻结</el-button>
          </el-form-item> -->
            <!-- <el-form-item>
            <el-button type="success" plain>批量解冻</el-button>
          </el-form-item> -->

          </el-form>
        </el-col>

        <!-- 表格内容 -->
        <el-table v-loading="loading" stripe :max-height="tableHeight" :data="initData.list" :header-cell-style="{'background-color': '#e8ecf1','color': '#0d2d84'}" :row-style="{'padding': '0px'}" :cell-style="{'padding': '5px'}">

          <el-table-column align="center" type="selection" width="55" v-if="Authcode == 101">
          </el-table-column>

          <!-- <el-table-column align="center" header-align='center' label="id" prop="id" width="55"></el-table-column> -->
          <el-table-column align="center" header-align='center' label="卡位编号" prop="seatid"></el-table-column>
          <el-table-column align="center" header-align='center' label="房间号" prop="roomnumber"></el-table-column>
          <el-table-column align="center" header-align='center' label="房间名" prop="roomname"></el-table-column>
          <el-table-column align="center" header-align='center' label="内线" prop="phonenumber"></el-table-column>
          <el-table-column align="center" header-align='center' label="IP地址" prop="ipaddress"></el-table-column>

          <el-table-column label="操作" align="center" width="140" fixed="right">
            <template slot-scope="scope">
              <div class="buttons">
                <!-- <el-button @click="showDetail(scope.row)" type="primary" size="mini" icon="el-icon-view"></el-button> -->
                <el-button @click="changeData(scope.row)" size="mini" icon="el-icon-edit"></el-button>
                <el-button @click="deleteData(scope.row)" type="danger" size="mini" icon="el-icon-delete" v-if="Authcode == 101"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-show="this.initData.total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="params.pageSize" :current-page="params.page" :page-sizes="pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="initData.total">
        </el-pagination>

        <!-- 新增/编辑座位 -->
        <el-dialog :visible.sync="dialog.edit" width="380px">
          <template slot="title">
            <div class="title">{{((key)=>{
            switch(key){
              case 0: return '新增座位';break;
              case 1: return '编辑座位';break;
            }
            })(editData.mode)}}</div>
          </template>
          <el-form :model="editData" label-width="100px" ref="editData" :rules="rules">

            <el-form-item label="卡位编号" prop="seatid">
              <el-input style="width: 200px" v-model="editData.seatid"></el-input>
            </el-form-item>
            <el-form-item label="房间号" prop="roomnuumber">
              <el-input style="width: 200px" v-model="editData.roomnumber"></el-input>
            </el-form-item>
            <el-form-item label="房间名" prop="roomname">
              <el-input style="width: 200px" v-model="editData.roomname"></el-input>
            </el-form-item>
            <el-form-item label="内线" prop="phonenumber">
              <el-input style="width: 200px" v-model="editData.phonenumber"></el-input>
            </el-form-item>
            <el-form-item label="IP地址" prop="ipaddress">
              <el-input style="width: 200px" v-model="editData.ipaddress"></el-input>
            </el-form-item>

            <div class="btns">
              <el-button type="primary" plain @click="submitData('editData')">提交</el-button>
              <el-button plain @click="dialog.edit = false">取消</el-button>
            </div>

          </el-form>
        </el-dialog>

      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'seat',
  data() {
    return {
      tableHeight: 0,
      isLogin: false,
      loading: false,
      lockD: false,
      lockS: false,
      pageSizes: [5, 10, 15, 20, 50, 100],
      initData: {
        list: [],
        // current: 1,
        total: 0
      },
      params: {
        page: 1,
        pageSize: 10,
        searchText: "",
        hasman: 0,
        // confirmdelete: 0
      },
      options: {
        // codition: [
        //   {
        //     label: '卡座编号',
        //     value: 'seatid'
        //   },
        //   {
        //     label: '房间号',
        //     value: 'roomnumber'
        //   },
        // ],
        hasman: [
          {
            label: '空座',
            value: 0,
          },
          {
            label: '非空座',
            value: 1,
          },
        ]
      },
      dialog: {
        edit: false,
        detail: false
      },
      // multipleSelection: [],
      editData: {
        mode: 0,
        id: '',
        seatid: "",
        roomnumber: "",
        roomname: "",
        ipaddress: "",
        phonenumber: ""
      },
      rules: {
        seatid: [{ validator: this.validSeatid, trigger: "blur" }],
        roomnumber: [{ validator: this.validRoomnumber, trigger: "blur" }],
        roomname: [{ validator: this.validRoomname, trigger: "blur" }],
        ipaddress: [{ validator: this.validIPaddress, trigger: "blur" }],
        phonenumber: [{ validator: this.validPhonenumber, trigger: "blur" }],
      },
      hasman: 1,
      searchText: '',
    }
  },
  created() {
    this.getUserInfo();
    this.init();
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = this.$refs.container.offsetHeight - 205;
      // console.log(this.tableHeight)
    })
  },
  computed: {
    Authcode() {
      return this.$cookies.get("__ac")
    },
  },
  methods: {
    init() {
      this.params = {
        page: 1,
        pageSize: 10,
        searchText: '',
        hasman: 1,
        // confirmdelete: 0,
      };
      // this.options.section = [];
      this.search()
    },
    // 获取用户数据
    getUserInfo() {
      let tokenString = this.$cookies.get("__tk");
      let authorizeCode = this.$cookies.get("__ac");
      if (!tokenString) {
        this.isLogin = false;
        this.$router.push('/home')
      } else {
        this.isLogin = true;
      }
      if (authorizeCode == 101 || authorizeCode == 301 || authorizeCode == 201) {
        this.isAdmin = true;

      } else {
        this.isAdmin = false;
        this.$router.push('/home')
      }

    },
    // 退出
    outLogin() {
      if (this.isLogin) {
        this.$cookies.keys().map((cookieName) => {
          this.$cookies.remove(cookieName);
        });
        this.isLogin = false;
        this.isAdmin = false;
        this.$message.success('退出成功');
        setTimeout(() => {
          this.$router.push({ name: 'home' });
        }, 500);
      } else {
        return
      }
    },
    // 查询
    search() {
      if (this.loading) {
        return
      }
      this.loading = true;
      this.axios({
        method: 'get',
        url: '/api/seatsoperations/',
        headers: {
          // 'Authorization': this.$cookies.get('__tk')
          'Token': this.$cookies.get('__tk')
        },
        params: {
          page: this.params.page,
          hasman: this.params.hasman,
          perpageitem: this.params.pageSize,
          searchText: this.params.searchText,
          username: this.$cookies.get('__un')
        }
      }).then(res => {
        // console.log(res)
        if (res.data.code == 200) {
          this.initData.list = res.data.data;
          this.initData.total = res.data.totalnum;
          // this.$message({
          //   message: '查询成功',
          //   type: 'success'
          // });
        } else {
          this.$message.warning(res.data.msg);
        }
        this.loading = false;

      }).catch(error => {
        this.$message.error(error || "出现错误，请稍后再试")
        // this.$cookies.keys().map((cookieName) => {
        //   this.$cookies.remove(cookieName);
        // });
        // this.$router.push('/home')
      });
    },
    // 改变搜索条件
    goSearch() {
      this.params.page = 1;
      this.params.hasman = this.hasman;
      this.params.searchText = this.searchText;
      this.search();
    },
    // 增加座位
    addSeat() {
      if (this.$refs.editData) {
        this.$refs.editData.resetFields();
        this.editData = {
          mode: 0, // 0==>添加  1==>修改
          // id: "",
          ipaddress: '',
          phonenumber: '',
          roomnumber: '',
          roomname: '',
          seatid: '',
          roomname: '',
        };
      }
      this.dialog.edit = true;
    },
    // 编辑座位
    changeData(o) {
      if (this.$refs.editData) {
        this.$refs.editData.resetFields();
      }
      this.editData = {
        mode: 1, // 0==>添加  1==>修改
        id: o.id,
        ipaddress: o.ipaddress,
        phonenumber: o.phonenumber,
        roomnumber: o.roomnumber,
        seatid: o.seatid,
        roomname: o.roomname,
      };
      this.dialog.edit = true;
    },
    // 删除座位
    deleteData(o) {
      this.axios({
        method: 'delete',
        url: '/api/seatsoperations/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        data: { seatid: o.seatid, confirmdelete: 0 }
      }).then(res => {
        if (res.data.code == 300) {
          this.$confirm(`${res.data.msg}, 是否确认删除?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.confirmDelete(o);
          }).catch(() => {
            this.$message.info('已取消删除')
          });
        } else if (res.data.code == 200) {
          this.$alert(`此卡座已分配人员(${res.data.data.name},${res.data.data.mobile})，继续此操作会一并删除员工信息，是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.confirmDelete(o);
          }).catch(() => {
            this.$message.info('已取消删除')
          });
        }

      }).catch(error => {
        this.$message.error(error || "出现错误，请稍后再试")
      });
    },
    // 确认删除
    confirmDelete(o) {
      this.axios({
        method: 'delete',
        url: '/api/seatsoperations/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        data: { seatid: o.seatid, confirmdelete: 1 }
      }).then(res => {
        if (res.data.code == 200) {
          this.$message.success('删除成功')
          this.search();
        }
      }).catch(error => {
        this.$message.error(error || "出现错误，请稍后再试")
      })
    },
    // 多选
    handleSelectionChange(v) {
      this.multipleSelection = v;
    },
    // 批量删除
    delSelections() {
      // console.log("批量删除==>", this.multipleSelection);
    },
    // 当前页
    handleCurrentChange(p) {
      this.params.page = p;
      this.search();
    },
    // 条/页
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.params.page = 1;
      this.search();
    },
    // 提交表单
    submitData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.editData.mode == 0) {
            // 新增请求
            let data = {
              seatid: this.editData.seatid,
              ipaddress: this.editData.ipaddress,
              phonenumber: this.editData.phonenumber,
              roomname: this.editData.roomname,
              roomnumber: this.editData.roomnumber,
            }
            this.axios({
              method: 'put',
              url: '/api/seatsoperations/',
              headers: {
                // 'Authorization': this.$cookies.get('__tk')
                'Token': this.$cookies.get('__tk')
              },
              data: data,
            }).then(res => {
              if (res.data.code == 200) {
                this.$message.success('新增成功')
                this.search();
                this.dialog.edit = false;
              } else {
                this.$message.warning(res.data.msg)
              }
            }).catch(error => {
              this.$message.error(error || "出现错误，请稍后再试")
            })

          } else {
            // 编辑请求
            let data = {
              id: this.editData.id,
              seatid: this.editData.seatid,
              ipaddress: this.editData.ipaddress,
              phonenumber: this.editData.phonenumber,
              roomname: this.editData.roomname,
              roomnumber: this.editData.roomnumber,
            }
            this.axios({
              method: 'post',
              url: '/api/seatsoperations/',
              headers: {
                // 'Authorization': this.$cookies.get('__tk')
                'Token': this.$cookies.get('__tk')
              },
              data: this.$qs.stringify(data),
            }).then(res => {
              if (res.data.code == 200) {
                this.$message.success('编辑成功')
                this.search();
                this.dialog.edit = false;
              } else {
                this.$message.warning(res.data.msg)
              }
            }).catch(error => {
              this.$message.error(error || "出现错误，请稍后再试")
            })
          }
        } else {
          this.$message.warning('请检查信息')
        }
      });
    },

    // --------------------------rules验证-----------------------------------
    // 验证卡位编号
    validSeatid(rule, value, callback) {
      if (value == "") {
        callback(new Error('卡位编号不能为空'))
      } else {
        let reg = /^[\da-zA-Z]{6,}$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的卡位编号"));
        } else {
          callback();
        }
      }
    },
    // 验证房间号
    validRoomnumber(rule, value, callback) {
      if (value != "") {
        let reg = /^([\d]{3,})|([\d]{3,}[a-zA-Z]{1})$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的房间号"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 验证房间名
    validRoomname(rule, value, callback) {
      if (value != "") {
        let reg = /^([\d]{3,})|([\d]{3,}[a-zA-Z]{1})|[\u4e00-\u9fa5·]{2,}$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的房间名"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 验证内线
    validPhonenumber(rule, value, callback) {
      if (value != "") {
        let reg = /^[0-9\-]{5,}$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的内线"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 验证IP地址
    validIPaddress(rule, value, callback) {
      if (value == "" || value == '暂无') {
        // callback(new Error("请输入IP地址"));
        callback();
      } else {
        let reg = /^([1-9]\d?|1\d{2}|2[0-4]\d|25[0-5])(\.([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])){3}$/;
        if (!reg.test(value)) {
          callback(new Error("IP地址有误!"));
        }
        callback();
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.seat {
  .container {
    padding: 20px;
    background-color: #fff;
    border-radius: 6px;
    height: calc(100% - 40px);
    .top {
      padding-bottom: 10px;
      margin-bottom: 10px;
      border-bottom: 1px solid #ccc;
      >>> .el-breadcrumb {
        font-size: 20px;
        height: 40px;
        line-height: 40px;
      }
    }
    >>> .el-table {
      margin-bottom: 10px;
    }
    >>> .el-pagination {
      text-align: center;
    }
    >>> .el-dialog {
      .title {
        font-size: 20px;
        height: 20px;
        line-height: 1;
        text-align: center;
        font-weight: bold;
        color: #000;
      }
      .el-dialog__body {
        padding: 20px 40px;
        label.el-form-item__label {
          text-align: justify;
          height: 40px;
          &::after {
            display: inline-block;
            width: 100%;
            content: "";
            height: 0;
          }
        }
        .el-form-item__content {
          position: relative;
          .el-tooltip {
            position: absolute;
            right: -25px;
            transform: translateY(50%);
          }
        }

        .btns {
          text-align: center;
          .el-button {
            width: 100px;
            height: 40px;

            & + .el-button {
              margin-left: 60px;
            }
          }
        }
      }
    }
  }
}
</style>